import { useState } from 'react'
import { Select } from 'antd'
import Fuse from 'fuse.js'
import path from 'path-browserify'
import { withRouter } from 'react-router-dom'
import { SearchOutlined } from '@ant-design/icons'
import router from '@/router'
import './HeaderSearch.less'

const { Option } = Select

function generateRoutes(routes, basePath = '/', prefixTitle = []) {
  let res = []

  for (const router of routes) {
    // skip hidden router
    if (router.hidden) { continue }

    const data = {
      path: path.resolve(basePath, router.path),
      title: [...prefixTitle]
    }

    // if (router.meta && router.meta.title) {
    if (router.key && router.title) {
      // data.title = [...data.title, router.meta.title]
      data.title = [...data.title, router.title]

      // if (router.redirect !== 'noRedirect') {
      if (!router.children || router.children.length === 0) {
        // only push the routes with title
        // special case: need to exclude parent router without redirect
        res.push(data)
      }
    }

    // recursive child routes
    if (router.children) {
      const tempRoutes = generateRoutes(router.children, data.path, data.title)
      if (tempRoutes.length >= 1) {
        res = [...res, ...tempRoutes]
      }
    }
  }
  return res
}

const routeList = generateRoutes(router)

// 本地搜索
const fuse = new Fuse(routeList, {
  shouldSort: true,
  threshold: 0.4,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [{
    name: 'title',
    weight: 0.7
  }, {
    name: 'path',
    weight: 0.3
  }]
})

// 搜索方法
function serchRoute(query) {
  if (query !== '') {
    return fuse.search(query)
  }
  return []
}




const HeaderSearch = (props) => {
  const [data, setData] = useState([])
  const [value, setValue] = useState(undefined)

  const handleSearch = value => {
    if (value) {
      const data = serchRoute(value)
      setData(data)
    } else {
      setData(data)
    }
  }
	
  const handleChange = value => {
    setValue(value)
    props.history.push(value)
  }
  const options = data.map(d => <Option key={d.item.path}>{d.item.title.join(' > ')}</Option>)
  return (
    <div className="header-search">
      <Select
        bordered={true}
        showSearch={true}
        suffixIcon={<SearchOutlined/>}
        value={value}
        placeholder={props.placeholder}
        style={props.style}
        defaultActiveFirstOption={false}
        filterOption={false}
        onSearch={handleSearch}
        onChange={handleChange}
        notFoundContent={null}>
        {options}
      </Select>
    </div>
  )
}

export default withRouter(HeaderSearch)